package com.framework.modules.base.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.framework.common.config.SystemConfigName;
import com.framework.common.utils.*;
import com.framework.form.RegisterForm;
import com.framework.modules.app.entity.MixedOnlineUserEntity;
import com.framework.modules.app.service.MixedOnlineUserService;
import com.framework.modules.base.entity.*;
import com.framework.modules.base.service.*;
import com.framework.modules.chat.entity.ChatFriendEntity;
import com.framework.modules.chat.service.ChatFriendService;
import com.framework.modules.dataview.entity.ViewUserGiftListEntity;
import com.framework.modules.dataview.service.ViewUserGiftListService;
import com.framework.modules.live.entity.LiveRewardsEntity;
import com.framework.modules.live.entity.LiveRoomEntity;
import com.framework.modules.live.service.LiveRewardsService;
import com.framework.modules.live.service.LiveRoomService;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.common.exception.RRException;
import com.framework.common.validator.Assert;
import com.framework.modules.base.dao.UserDao;
import com.framework.form.LoginForm;
import org.springframework.transaction.annotation.Transactional;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private TokenService tokenService;

	@Autowired
	private UserVipinfoService userVipinfoService;

	@Autowired
	private UserSpaceService userSpaceService;

	@Autowired
	private ChatFriendService chatFriendService;

	@Autowired
	private UserGiftService userGiftService;

	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private GiftService giftService;

	@Autowired
	private UserBalanceService userBalanceService;

	@Autowired
	private LiveRoomService liveRoomService;

	@Autowired
	private LiveRewardsService liveRewardsService;

	@Autowired
	private UserGiftHistoryService userGiftHistoryService;

	@Autowired
	private ViewUserGiftListService viewUserGiftListService;

	@Autowired
	private UserDoingService userDoingService;

	@Autowired
	private MixedOnlineUserService mixedOnlineUserService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		Page<UserEntity> page = this.selectPage(
				new Query<UserEntity>(params).getPage(),
				new EntityWrapper<UserEntity>()
		);

		return new PageUtils(page);
	}

	@Override
	public UserEntity queryByUsername(String username) {
		return queryByMobile(username);
	}

	@Override
	public UserEntity queryByMobile(String mobile) {
		UserEntity userEntity = new UserEntity();
		userEntity.setMobile(mobile);
		return baseMapper.selectOne(userEntity);
	}

	@Override
	public Integer insertAndGetUserId(UserEntity entity){
		return baseMapper.insertAndGetUserId(entity);
	}

	@Override
	public Object updateMobile(Long uid,String mobile) {
		UserEntity entity=new UserEntity();
		//1.更新手机号码和username
		entity.setUserId(uid);
		entity.setUsername(MySeq.getUsername());
		entity.setMobile(mobile);
		this.baseMapper.updateById(entity);
		//2.删除token
		return tokenService.deleteById(entity.getUserId());
	}

	@Override
	public Object statAttentInfo(Long uid) {
		Map<String,Object> result=new HashMap<>();
		Integer attentedCount=0;
		Integer fansCount=0;
		UserSpaceEntity userSpaceEntity=userSpaceService.selectById(uid);
		if(userSpaceEntity!=null){
			attentedCount=userSpaceEntity.getAttentCount();
			fansCount=userSpaceEntity.getFansCount();
		}
		Integer friendCount=chatFriendService.selectCount(new EntityWrapper<ChatFriendEntity>()
				.eq("uid",uid).eq("state",1));
		//获取看过的我的人的数量
		Integer lookMeCount=userDoingService.selectCount(new EntityWrapper<UserDoingEntity>()
				.eq("uid",uid).eq("type","look")
				.eq("object_name","user"));
		//获取我看过的人数量
		Integer myLookCount=userDoingService.selectCount(new EntityWrapper<UserDoingEntity>()
				.eq("object_uid",uid).eq("type","look")
				.eq("object_name","user"));
		//获取我喜欢的人数量
		Integer mylikeCount=userDoingService.selectCount(new EntityWrapper<UserDoingEntity>()
				.eq("uid",uid).eq("type","like")
				.eq("object_name","user"));
		//获取喜欢我的人数量
		Integer likeMeCount=userDoingService.selectCount(new EntityWrapper<UserDoingEntity>()
				.eq("object_uid",uid).eq("type","like")
				.eq("object_name","user"));
		result.put("attented_count",attentedCount);
		result.put("fans_count",fansCount);
		result.put("friend_count",friendCount);
		result.put("look_me_count",lookMeCount);
		result.put("my_look_count",myLookCount);
		result.put("my_like_count",mylikeCount);
		result.put("like_me_count",likeMeCount);
		return result;
	}

	@Override
	@Transactional
	public ResponseCode sendGift(Long uid, String giftId, Integer quantity, String targetUid) {

		//1.查询礼物价格
		GiftEntity giftEntity = giftService.selectById(giftId);
		if (giftEntity == null) {
			return ResponseCode.FAIL;
		}
		int price = giftEntity.getPrice() * quantity;

		// 2.查询用户金币余额
		UserBalanceEntity userBalanceEntity = userBalanceService.selectById(uid);
		if (userBalanceEntity == null) {
			return ResponseCode.ERROR_COIN_NOT_ENOUGH;
		}
		int coin = userBalanceEntity.getCoin();
		// 3.判断金币是否足够
		if (coin < price) {
			return ResponseCode.ERROR_COIN_NOT_ENOUGH;
		}
		UserBalanceEntity userBalanceEntity1 = new UserBalanceEntity();
		userBalanceEntity1.setUid(uid.intValue());
		userBalanceEntity1.setCoin(coin - price);
		//4.更新金币余额
		if (userBalanceService.updateById(userBalanceEntity1)) {
			//4.插入用户送礼记录表
			UserGiftHistoryEntity userGiftHistoryEntity = new UserGiftHistoryEntity();
			userGiftHistoryEntity.setUid(uid.intValue());
			userGiftHistoryEntity.setObjectId(giftId);
			userGiftHistoryEntity.setObjectName(giftEntity.getName());
			userGiftHistoryEntity.setObjectValue(price);
			userGiftHistoryEntity.setObjectQuantity(quantity);
			userGiftHistoryEntity.setTargetUid(Integer.valueOf(targetUid));
			userGiftHistoryEntity.setAdddate(DateUtils.getSecondTimestamp(new Date()));
			userGiftHistoryService.insert(userGiftHistoryEntity);
			// 5.查询直播间信息
			LiveRoomEntity liveRoomEntity = liveRoomService.selectById(targetUid);
			LiveRewardsEntity liveRewardsEntity = new LiveRewardsEntity();
			liveRewardsEntity.setUid(liveRoomEntity.getUid());
			liveRewardsEntity.setFromUid(uid.intValue());
			liveRewardsEntity.setLiveRoundId(liveRoomEntity.getLiveRoundId());
			liveRewardsEntity.setObjectId(giftId);
			liveRewardsEntity.setObjectQuantity(quantity);
			liveRewardsEntity.setObjectName(giftEntity.getName());
			//收益为友豆
			liveRewardsEntity.setObjectValue(price*QuickHelper.getConfigIntegerValue(SystemConfigName.PAY_RATE_COIN2BEAN));
			liveRewardsEntity.setAdddate(DateUtils.getSecondTimestamp(new Date()));
			// 6.插入直播收支记录 ，
			liveRewardsService.insert(liveRewardsEntity);
			return ResponseCode.SUCCESS;
		}
		return ResponseCode.FAIL;
	}

	@Transactional
	public ResponseCode sendGift2LiveRoom(Long uid, Integer giftId, Integer quantity, String targetUid) {

		//1.查询礼物价格
		GiftEntity giftEntity = giftService.selectById(giftId);
		if (giftEntity == null) {
			return ResponseCode.FAIL;
		}

		//购买礼物消耗的金币数
		int total = giftEntity.getPrice() * quantity;

		// 2.查询用户金币余额
		UserBalanceEntity userBalanceEntity = userBalanceService.selectById(uid);
		if (userBalanceEntity == null) {
			return ResponseCode.ERROR_COIN_NOT_ENOUGH;
		}

		int mycoin = userBalanceEntity.getCoin();

		// 3.判断金币是否足够
		if (mycoin < total) {
			return ResponseCode.ERROR_COIN_NOT_ENOUGH;
		}

		//更新余额
		UserBalanceEntity newBalanceEntity = new UserBalanceEntity();
		newBalanceEntity.setUid(uid.intValue());
		newBalanceEntity.setCoin(mycoin - total);

		//4.更新金币余额
		if (userBalanceService.updateById(newBalanceEntity)) {

			//4.插入用户送礼记录表
			UserGiftHistoryEntity userGiftHistoryEntity = new UserGiftHistoryEntity();
			userGiftHistoryEntity.setUid(uid.intValue());
			userGiftHistoryEntity.setObjectId(giftId.toString());
			userGiftHistoryEntity.setObjectName(giftEntity.getName());
			userGiftHistoryEntity.setObjectValue(total);
			userGiftHistoryEntity.setObjectQuantity(quantity);
			userGiftHistoryEntity.setTargetUid(Integer.valueOf(targetUid));
			userGiftHistoryEntity.setAdddate(DateUtils.getSecondTimestamp(new Date()));
			userGiftHistoryService.insert(userGiftHistoryEntity);

			// 5.查询直播间信息
			LiveRoomEntity liveRoomEntity = liveRoomService.selectById(targetUid);
			LiveRewardsEntity liveRewardsEntity = new LiveRewardsEntity();
			liveRewardsEntity.setUid(liveRoomEntity.getUid());
			liveRewardsEntity.setFromUid(uid.intValue());
			liveRewardsEntity.setLiveRoundId(liveRoomEntity.getLiveRoundId());
			liveRewardsEntity.setObjectId(giftId.toString());
			liveRewardsEntity.setObjectQuantity(quantity);
			liveRewardsEntity.setObjectName(giftEntity.getName());
			//收益为友豆
			liveRewardsEntity.setObjectValue(total*QuickHelper.getConfigIntegerValue(SystemConfigName.PAY_RATE_COIN2BEAN));
			liveRewardsEntity.setAdddate(DateUtils.getSecondTimestamp(new Date()));

			// 6.插入直播收支记录 ，
			liveRewardsService.insert(liveRewardsEntity);
			return ResponseCode.SUCCESS;
		}
		return ResponseCode.FAIL;
	}

	@Override
	public ResponseCode sendUserGift(Long uid, String giftId, Integer quantity, String targetUid) {
		ViewUserGiftListEntity viewUserGiftListEntity=viewUserGiftListService.selectOne(new EntityWrapper<ViewUserGiftListEntity>().eq("id",giftId).eq("state",0).gt("expire_date",DateUtils.getSecondTimestamp(new Date())));
		if(viewUserGiftListEntity==null){
			return ResponseCode.FAIL;
		}
		int gifgtQuantity=viewUserGiftListEntity.getQuantity();

		gifgtQuantity=gifgtQuantity-quantity;
		if(gifgtQuantity<0){
			return ResponseCode.FAIL;
		}
		UserGiftEntity userGiftEntity1=new UserGiftEntity();
		if(gifgtQuantity==0){
			userGiftEntity1.setState("0");
		}
		userGiftEntity1.setQuantity(gifgtQuantity);
		userGiftEntity1.setUid(uid.intValue());
		userGiftService.updateById(userGiftEntity1);

		//1.插入用户送礼记录表
		UserGiftHistoryEntity userGiftHistoryEntity=new UserGiftHistoryEntity();
		userGiftHistoryEntity.setObjectId(giftId);
		userGiftHistoryEntity.setObjectName(viewUserGiftListEntity.getName());
		userGiftHistoryEntity.setObjectQuantity(quantity);
		userGiftHistoryEntity.setObjectValue(viewUserGiftListEntity.getGiftPrice()*quantity);
		userGiftHistoryEntity.setTargetUid(Integer.valueOf(targetUid));
		userGiftHistoryEntity.setAdddate(DateUtils.getSecondTimestamp(new Date()));
		userGiftHistoryService.insert(userGiftHistoryEntity);

		// 2.查询直播间信息
		LiveRoomEntity liveRoomEntity=liveRoomService.selectById(targetUid);
		LiveRewardsEntity liveRewardsEntity=new LiveRewardsEntity();
		liveRewardsEntity.setUid(liveRoomEntity.getUid());
		liveRewardsEntity.setFromUid(uid.intValue());
		liveRewardsEntity.setLiveRoundId(liveRoomEntity.getLiveRoundId());
		liveRewardsEntity.setObjectId(giftId);
		liveRewardsEntity.setObjectQuantity(quantity);
		liveRewardsEntity.setObjectName(viewUserGiftListEntity.getName());

		liveRewardsEntity.setObjectValue(viewUserGiftListEntity.getGiftPrice()*quantity*QuickHelper.getConfigIntegerValue(SystemConfigName.PAY_RATE_COIN2BEAN));
		liveRewardsEntity.setAdddate(DateUtils.getSecondTimestamp(new Date()));
		// 6.插入直播收支记录 ，
		liveRewardsService.insert(liveRewardsEntity);

		return ResponseCode.SUCCESS;
	}


	@Override
	@Transactional
	public Long register(RegisterForm form){
		Long uid = 0l;

		try {
			String mobile = form.getMobile();

			//1.插入到 tb_user 表
			Boolean bRegister = false;
			UserEntity entity = new UserEntity();
			entity.setUsername(MySeq.getUsername());
			entity.setMobile(mobile);
			entity.setPassword(DigestUtils.sha256Hex(UUID.randomUUID().toString()));
			entity.setCreateTime(new Date());
			Integer rows = this.insertAndGetUserId(entity);

			//1.获得主键ID
			uid = entity.getUserId();



			//2.插入到 tb_user_info 表 pc端注册需要
			if("web".equals(form.getPlatform())){
				UserInfoEntity defaultUserInfo = new UserInfoEntity();
				defaultUserInfo.setUid(uid.intValue());
				defaultUserInfo.setIsVerifyIdcard(0);
				JSONObject obj = QuickHelper.getConfigJSONObject(SystemConfigName.ASSETS_USER_DEFAULTAVATAR);
				JSONArray jsonArray = obj.getJSONArray("list");
				Random random=new Random();
				int rand=random.nextInt(jsonArray.size()-1);
				defaultUserInfo.setAvanta(jsonArray.getString(rand));
				userInfoService.insert(defaultUserInfo);
			}
			//this.baseMapper.newUserInfo(uid,1);


			//3.插入到 tb_user_balance
			this.baseMapper.newUserBalance(uid,new BigDecimal(0.0),new BigDecimal(0.0), DateUtils.getSecondTimestamp(new Date()));

			/**
			 * 4.插入 tb_user_vip_info
			 * 需要查询非会员的匹配次数
			 */
			JSONObject matchingConfig = QuickHelper.getConfigJSONObject(SystemConfigName.ASSETS_MATCHING_DAILY_LIMIT);
			UserVipinfoEntity vipinfo = new UserVipinfoEntity();
			vipinfo.setUid(Integer.valueOf(uid.toString()));
			vipinfo.setDailyInterestSearchCount(matchingConfig.getInteger("interest"));
			vipinfo.setDailySenceSearchCount(matchingConfig.getInteger("sence"));
			vipinfo.setDailyVoiceSearchCount(matchingConfig.getInteger("voice"));
			vipinfo.setDailyLocationSearchCount(matchingConfig.getInteger("location"));
			userVipinfoService.insert(vipinfo);

			TokenEntity tokenEntity = new TokenEntity();
			tokenEntity.setToken("-");
			tokenEntity.setUserId(Long.valueOf(uid.toString()));
			this.baseMapper.newUserToken(tokenEntity);

		}catch (Exception e){
			throw new RRException(e.getMessage());
		}

		//userInfoService.insert()

		return uid;
	}

	@Override
	public Map<String, Object> login(LoginForm form) {

		//登录模式,默认是手机验证码模式登录
		String mode = form.getMode();

		UserEntity user = this.baseMapper.queryByUsernameOrMobile(form.getUsername());
		Assert.isNull(user, "用户名/手机号或密码错误");

		//如果是普通的密码登录模式
		if(mode.equals("normal")) {
			String password = DigestUtils.sha256Hex(form.getPassword());

			// 密码错误
			if (!user.getPassword().equals(password)) {
				throw new RRException("用户名/手机号或密码错误");
			}
		}


		if(mode.equals("mobile")){

		}

		Long uid = user.getUserId();

		// 获取登录token
		TokenEntity tokenEntity = tokenService.createToken(user.getUserId(),form.getPlatform());
		Integer expire = DateUtils.getSecondTimestamp(tokenEntity.getExpireTime());
		String token = tokenEntity.getToken();

		//签名生成，需要在拦截器中解密以及放入request中去
		/*Map<String,Object> signMap  = new HashMap<String,Object>();
		signMap.put("uid",user.getUserId().toString());
		signMap.put("token",token);
		signMap.put("expire",expire);

		String text = JSON.toJSONString(signMap);
		String sign = DESCryptUtils.encrypt(token,text);*/

		Map<String, Object> map = new HashMap<>(2);
		map.put("token", token);
		map.put("expire", expire);

		//更新本次登录时间
		UserEntity ue = new UserEntity();
		ue.setLastLogin(new Date());
		ue.setUserId(user.getUserId());

		this.updateById(ue);

		/**
		 * 写入在线用户表
		 */

		MixedOnlineUserEntity mouEntity =  mixedOnlineUserService.selectById(uid);
		if(mouEntity ==null) {
			mouEntity = new MixedOnlineUserEntity();
			mouEntity.setUid(Integer.valueOf(uid.toString()));
			mouEntity.setAdddate(QuickHelper.getNowTimeStampSeconds());
			mouEntity.setLastUptime(mouEntity.getAdddate());
			mouEntity.setIsOnline(1);
			mixedOnlineUserService.insert(mouEntity);
		}
		mouEntity.setIsOnline(1);
		mouEntity.setLastUptime(QuickHelper.getNowTimeStampSeconds());
		mixedOnlineUserService.updateById(mouEntity);

		return map;
	}



}
